package com.example.blue;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

// BluetoothService.java
public class BluetoothService extends Service {
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothGatt bluetoothGatt;
    private BluetoothDevice connectedDevice;
    private String TAG="bluetooth service";
    private final IBinder binder = new LocalBinder();
    private static final UUID SERVICE_UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // 示例：设备信息服务
    // TODO: 将此处的 UUID 替换为你想要接收通知的特征的 UUID
    private static final UUID CHARACTERISTIC_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // 示例：制造商名称特征
    private static final UUID CCC_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
//    private final ConcurrentLinkedQueue<byte[]>  dataQueueLeft = new ConcurrentLinkedQueue<>();
//    private final ConcurrentLinkedQueue<byte[]>  dataQueueRight = new ConcurrentLinkedQueue<>();
    private final LinkedBlockingDeque<byte[]> dataQueueLeft = new LinkedBlockingDeque<>();
    private final LinkedBlockingDeque<byte[]> dataQueueRight = new LinkedBlockingDeque<>();

    public static final String ACTION_CONNECTEDLEFT = "com.example.bluetooth.ACTION_CONNECTEDLEFT";
    public static final String ACTION_CONNECTEDRIGHT = "com.example.bluetooth.ACTION_CONNECTEDRIGHT";
    public static final String ACTION_DISCONNECTEDLEFT = "com.example.bluetooth.ACTION_DISCONNECTEDLEFT";
    public static final String ACTION_DISCONNECTEDRIGHT = "com.example.bluetooth.ACTION_DISCONNECTEDRIGHT";
    public static final String ACTION_DATA_AVAILABLE = "com.example.bluetooth.ACTION_DATA_AVAILABLE";
    private Boolean isSendBroadcast=false;

    public class LocalBinder extends Binder {
        public BluetoothService getService() {
            return BluetoothService.this;
        }
    }
    public static ExecutorService newBleReceiverPool() {
        return Executors.newSingleThreadExecutor();
    }
    public static ExecutorService newBleReceiverPoolRight() {
        return Executors.newSingleThreadExecutor();
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    public LinkedBlockingDeque<byte[]> getDataQueueLeft() {

        return dataQueueLeft;
    }
    public LinkedBlockingDeque<byte[]> getDataQueueRight() {

        return dataQueueRight;
    }

    // 定义回调接口
    public interface OnDataReceiveListener {
        void onDataReceived(byte[] data, int deviceIndex);
    }

    private OnDataReceiveListener listener;

    public void setOnDataReceiveListener(OnDataReceiveListener l) {
        this.listener = l;
    }

    @Override
    public void onCreate() {
        Log.i("Tag","start service");
        super.onCreate();
        CrashHandler.getInstance().init(this);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//        gattThread = new HandlerThread("BluetoothGattThread");
//        gattThread.start();
//        gattHandler = new Handler(gattThread.getLooper());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 可以从 Intent 中获取需要连接的设备地址等信息并连接
        String deviceAddress = intent.getStringExtra("DEVICE_ADDRESS_LEFT");
        if (deviceAddress != null) {
            new Thread(() -> {
                // 耗时操作，比如蓝牙连接
                try {
                    connectToDevice1(deviceAddress);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        String deviceAddress2 = intent.getStringExtra("DEVICE_ADDRESS_RIGHT");
        if (deviceAddress2 != null) {
            new Thread(() -> {
                // 耗时操作，比如蓝牙连接
                try {
                    connectToDevice2(deviceAddress2);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        // START_STICKY 表示服务被异常杀死后尝试重新创建
        return START_STICKY;
    }
// ⭐ 加上这个方法，专门通知 Activity
    private void handleDataFromDevice(int deviceIndex, byte[] data) {
        if (listener != null && data != null) {
            listener.onDataReceived(data, deviceIndex);
        }
    }
    private void connectToDevice1(String deviceAddress) throws IOException {

//        if (bluetoothAdapter.isDiscovering()) {
//            bluetoothAdapter.cancelDiscovery();
//        }
//        if (bluetoothGatt != null) {
//            bluetoothGatt.close();
//        }
        connectedDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
        bluetoothGatt = connectedDevice.connectGatt(this, false, gattCallback1);

    }

    private void connectToDevice2(String deviceAddress) throws IOException {

//        if (bluetoothAdapter.isDiscovering()) {
//            bluetoothAdapter.cancelDiscovery();
//        }
//        if (bluetoothGatt != null) {
//            bluetoothGatt.close();
//        }
        connectedDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
        bluetoothGatt = connectedDevice.connectGatt(this, false, gattCallback2);

    }
//    private void connectToDevice(String deviceAddress) throws IOException {
//
//        if (bluetoothAdapter.isDiscovering()) {
//            bluetoothAdapter.cancelDiscovery();
//        }
//        if (bluetoothGatt != null) {
//            bluetoothGatt.close();
//        }
//        connectedDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
//        bluetoothGatt = connectedDevice.connectGatt(this, false, gattCallback);
//        gattMap.put(deviceAddress, bluetoothGatt);
//
//    }

    private final BluetoothGattCallback gattCallback1 = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String addr = gatt.getDevice().getAddress();
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功
                Log.d(TAG, "成功连接到 GATT 服务器");
                Intent intent = new Intent(ACTION_CONNECTEDLEFT);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // 连接断开
                Intent intent = new Intent(ACTION_DISCONNECTEDLEFT);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                Log.d(TAG, "与 GATT 服务器断开连接");
                isSendBroadcast=false;
                dataQueueLeft.clear();
                dataQueueRight.clear();
                gatt.close();
            }
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功");
                //  handler.post(() -> statusTextView.setText("服务发现成功！正在订阅通知..."));
                // 查找特定的服务和特征
                BluetoothGattCharacteristic characteristic = findCharacteristic(gatt);
                if (characteristic != null) {
                    // 启用通知
                    gatt.setCharacteristicNotification(characteristic, true);
                    // 写入描述符以启用通知
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_UUID);

                    if (descriptor != null) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                } else {
                    //  handler.post(() -> statusTextView.setText("未找到所需的特征。"));
                }
            } else {
                Log.e(TAG, "服务发现失败，状态码：" + status);
                // handler.post(() -> statusTextView.setText("服务发现失败。"));
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            String addr = gatt.getDevice().getAddress();
            // 接收到通知数据
             byte[] data =  characteristic.getValue();
            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("isLeftDeviceReceived", true);
            editor.apply();
            if(isSendBroadcast==false) {

                Intent intent = new Intent(ACTION_DATA_AVAILABLE);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                isSendBroadcast=true;
            }
            System.out.println("bluetooth----:"+utils.bytesToHex(data));
            newBleReceiverPool().execute(()->{
                dataQueueLeft.pollLast();
                dataQueueLeft.offerFirst(data);
            });



        }

        private BluetoothGattCharacteristic findCharacteristic(BluetoothGatt gatt) {
            // 遍历所有服务，找到匹配的 UUID
            for (BluetoothGattService service : gatt.getServices()) {
                if (service.getUuid().equals(SERVICE_UUID)) {
                    // 找到目标服务，遍历其特征
                    return service.getCharacteristic(CHARACTERISTIC_UUID);
                }
            }
            return null;
        }
    };
    private final BluetoothGattCallback gattCallback2 = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String addr = gatt.getDevice().getAddress();
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功
                Log.d(TAG, "成功连接到 GATT 服务器");
                Intent intent = new Intent(ACTION_CONNECTEDRIGHT);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // 连接断开
                Intent intent = new Intent(ACTION_DISCONNECTEDRIGHT);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                Log.d(TAG, "与 GATT 服务器断开连接");
                isSendBroadcast=false;
                dataQueueLeft.clear();
                dataQueueRight.clear();
                gatt.close();
            }
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功");
                //  handler.post(() -> statusTextView.setText("服务发现成功！正在订阅通知..."));
                // 查找特定的服务和特征
                BluetoothGattCharacteristic characteristic = findCharacteristic(gatt);
                if (characteristic != null) {
                    // 启用通知
                    gatt.setCharacteristicNotification(characteristic, true);
                    // 写入描述符以启用通知
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_UUID);

                    if (descriptor != null) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                } else {
                    //  handler.post(() -> statusTextView.setText("未找到所需的特征。"));
                }
            } else {
                Log.e(TAG, "服务发现失败，状态码：" + status);
                // handler.post(() -> statusTextView.setText("服务发现失败。"));
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            String addr = gatt.getDevice().getAddress();
           // System.out.println("onCharacteristicChanged:"+addr);
            // 接收到通知数据

            byte[] data =  characteristic.getValue();
            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("isRightDeviceReceived", true);
            editor.apply();
            if(isSendBroadcast==false) {
                Intent intent = new Intent(ACTION_DATA_AVAILABLE);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
                isSendBroadcast=true;
            }
            newBleReceiverPoolRight().execute(()->{
                dataQueueRight.pollLast();
                dataQueueRight.offerFirst(data);
            });
            System.out.println("bluetooth----2:"+utils.bytesToHex(data));


        }


        private BluetoothGattCharacteristic findCharacteristic(BluetoothGatt gatt) {
            // 遍历所有服务，找到匹配的 UUID
            for (BluetoothGattService service : gatt.getServices()) {
                if (service.getUuid().equals(SERVICE_UUID)) {
                    // 找到目标服务，遍历其特征
                    return service.getCharacteristic(CHARACTERISTIC_UUID);
                }
            }
            return null;
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bluetoothGatt != null) {
            bluetoothGatt.close();
        }
    }
    // 子线程：接收和发送数据

}

